package doan.chuyennganh.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import doan.chuyennganh.model.ClassStudent;

public class ListClassDataSource {
	private String TABLE_NAME = "tblClass";
	public static final String COLUMN_CLASS_ID = "class_id";
	public static final String COLUMN_CLASS_NAME = "class_name";
	public static final String COLUMN_CLASS_PERIODS = "class_periods";
	private int dbVersion;
	private ArrayList<ClassStudent> listClass = new ArrayList<ClassStudent>();
	// Database creation sql statement
	private String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
			+ "(" + COLUMN_CLASS_ID + " TEXT PRIMARY KEY, " + COLUMN_CLASS_NAME
			+ " TEXT, " + COLUMN_CLASS_PERIODS + " INTEGER DEFAULT(0) " + ")";

	// Database fields
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	private Set<String> tableNames = new HashSet<String>();
	private String[] allColumns = { COLUMN_CLASS_ID, COLUMN_CLASS_NAME, COLUMN_CLASS_PERIODS };

	public ListClassDataSource(Context context, String tableName) {
		TABLE_NAME = TABLE_NAME + tableName;
		CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
				+ COLUMN_CLASS_ID + " TEXT PRIMARY KEY, " + COLUMN_CLASS_NAME
				+ " TEXT, " + COLUMN_CLASS_PERIODS + " INTEGER DEFAULT(0) "
				+ ")";
		SharedPreferenceHelper pre = new SharedPreferenceHelper(context);
		dbVersion = pre.getInt(Constants.DATABASE_VERSION, 1);
		tableNames = pre.getStringSet(Constants.DATABASE_TABLES,
				new HashSet<String>());
		if (!tableNames.contains(TABLE_NAME)) {
			dbVersion += 1 ;
			tableNames.add(TABLE_NAME);
			pre.putInt(Constants.DATABASE_VERSION, dbVersion);
			pre.putStringSet(Constants.DATABASE_TABLES, tableNames);
		}
		Log.d("DBVERSION", dbVersion + "");
		dbHelper = new DatabaseHelper(context, TABLE_NAME, CREATE_TABLE,
				dbVersion);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
		listClass = (ArrayList<ClassStudent>) getAllClass();
	}

	public void openForReadOnly() {
		database = dbHelper.getReadableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public long insertClass(ClassStudent classStudent) {
		ClassStudent cls = getClass(classStudent.getMalop());
		if(cls != null){
			return -1;
		}
		ContentValues values = new ContentValues();
		values.put(COLUMN_CLASS_ID, classStudent.getMalop());
		values.put(COLUMN_CLASS_NAME, classStudent.getTenmonhoc());
		values.put(COLUMN_CLASS_PERIODS, classStudent.getTongsotiet());
		return database.insert(TABLE_NAME, null, values);
	}

	public void deleteClass(ClassStudent classStudent) {
		String id = classStudent.getMalop();
		if (getClass(classStudent.getMalop()) == null) {
			return;
		}
		database.delete(TABLE_NAME, COLUMN_CLASS_ID + " = " + id, null);
	}

	public void deleteClass(String classID) {
		if (getClass(classID) == null) {
			return;
		}
		database.delete(TABLE_NAME, COLUMN_CLASS_ID + " = " + classID, null);
	}

	private ClassStudent getClass(String id) {
		for (ClassStudent cls : listClass) {
			if (cls.getMalop().equalsIgnoreCase(id)) {
				return cls;
			}
		}
		return null;
	}

	public int updateClass(ClassStudent classStudent) {
		if (getClass(classStudent.getMalop()) == null) {
			return -1;
		}
		ContentValues cv = new ContentValues();
		cv.put(COLUMN_CLASS_ID, classStudent.getMalop());
		cv.put(COLUMN_CLASS_NAME, classStudent.getTenmonhoc());
		cv.put(COLUMN_CLASS_PERIODS, classStudent.getTongsotiet());
		return database.update(TABLE_NAME, cv, COLUMN_CLASS_ID + "=?",
				new String[] { String.valueOf(classStudent.getMalop()) });
	}

	public int updateValue(String id, String column, boolean value) {
		if (getClass(id) == null) {
			return -1;
		}
		ContentValues cv = new ContentValues();
		cv.put(column, value);
		return database.update(TABLE_NAME, cv, COLUMN_CLASS_ID + "=?",
				new String[] { String.valueOf(id) });
	}

	public List<ClassStudent> getAllClass() {
		List<ClassStudent> allclass = new ArrayList<ClassStudent>();

		Cursor cursor = database.query(TABLE_NAME, allColumns, null, null,
				null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			ClassStudent classStudent = cursorToClass(cursor);
			allclass.add(classStudent);
			cursor.moveToNext();
		}
		// make sure to close the cursor
		cursor.close();
		return allclass;
	}

	public void insertColumn(String new_col, ArrayList<String> checkList) {

		Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME
				+ " LIMIT 0", null);
		Log.d("COLUMNS", cursor.getColumnNames().toString());
		String[] colNames = cursor.getColumnNames();
		boolean isColumnExist = false;
		for (String col : colNames) {
			if (col.equalsIgnoreCase(new_col)) {
				isColumnExist = true;
				break;
			}
		}

		if (!isColumnExist) {
			String INSERT_COLUMN = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN "
					+ new_col + " BOOL DEFAULT (0)";
			database.execSQL(INSERT_COLUMN);
		}

		for (String ms : checkList) {
			updateValue(ms, new_col, true);
		}
	}

	private ClassStudent cursorToClass(Cursor cursor) {
		ClassStudent classStudent = new ClassStudent();
		classStudent.setMalop(cursor.getString(0));
		classStudent.setTenmonhoc(cursor.getString(1));
		classStudent.setTongsotiet(cursor.getInt(2));
		return classStudent;
	}

	public String[] getAllColumnsName() {
		Cursor dbCursor = database.query(TABLE_NAME, null, null, null, null,
				null, null);
		String[] columnNames = dbCursor.getColumnNames();
		return columnNames;
	}

	public void createExample() {
//		ClassStudent st1 = new ClassStudent("11111111", "Do Hoa May Tinh");
//		ClassStudent st2 = new ClassStudent("22222222",
//				"Lap Trinh Huong Doi Tuong");
//		ClassStudent st3 = new ClassStudent("33333333", "Co So Tri Thuc");
//		ClassStudent st4 = new ClassStudent("44444444", "Ngon Ngu Lap Trinh");
//		ClassStudent st5 = new ClassStudent("55555555", "ASM");
//		insertClass(st1);
//		insertClass(st2);
//		insertClass(st3);
//		insertClass(st4);
//		insertClass(st5);
	}
}
